package com.xxh.search.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxh.common.constant.SearchConstants;
import com.xxh.dataaccess.dao.VideoDao;
import com.xxh.dataaccess.dto.MovieDto;
import com.xxh.dataaccess.entity.User;
import com.xxh.dataaccess.entity.Video;
import com.xxh.search.dao.MovieRep;
import com.xxh.search.dao.UserRep;
import com.xxh.search.dao.VideoRep;
import com.xxh.search.document.MovieDocument;
import com.xxh.search.document.UserDocument;
import com.xxh.search.document.VideoDocument;
import com.xxh.search.service.SearchService;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("SearchService")
public class SearchServiceImpl implements SearchService {


    @Autowired
    MovieRep movieRep;

    @Autowired
    VideoRep videoRep;

    @Autowired
    UserRep userRep;

    @Autowired
    MongoTemplate mongoTemplate;


    @Override
    public int initMovieEsData(List<MovieDto> records) {
        if (records == null || records.isEmpty()) {
            return 0;
        }
        List<MovieDocument> documents = new ArrayList<>();
        records.stream().forEach(movieDto -> {
            MovieDocument document = new MovieDocument();
            BeanUtils.copyProperties(movieDto, document);
            documents.add(document);
        });
        movieRep.saveAll(documents);
        return documents.size();
    }


    @Override
    public int initVideoEsDate(List<Video> records) {
        if (records == null || records.isEmpty()) {
            return 0;
        }
        List<VideoDocument> documents = new ArrayList<>();
        records.stream().forEach(movieDto -> {
            VideoDocument document = new VideoDocument();
            BeanUtils.copyProperties(movieDto, document);
            documents.add(document);
        });
        videoRep.saveAll(documents);
        return documents.size();
    }

    @Override
    public int initUserEsData(List<User> records) {
        if (records == null || records.isEmpty()) {
            return 0;
        }
        List<UserDocument> documents = new ArrayList<>();
        records.stream().forEach(movieDto -> {
            UserDocument document = new UserDocument();
            BeanUtils.copyProperties(movieDto, document);
            documents.add(document);
        });
        userRep.saveAll(documents);
        return documents.size();
    }

    /**
     * @param page
     * @param keyword
     * @param type    搜索类型（电影|用户|视频）
     * @return
     */
    @Override
    public IPage search(Page page, String keyword, String type) {
        // jpa 分页从 0 开始
        Long current = page.getCurrent() - 1;
        Long size = page.getSize();
        //拿到分页信息，mybatics plus 的page 转为 jpa 的page
        Pageable pageable = PageRequest.of(current.intValue(), size.intValue());
        IPage pageData = null;

        switch (type) {
            case SearchConstants.User:
                //构建搜索条件
                MultiMatchQueryBuilder builder = QueryBuilders.multiMatchQuery(keyword, "username", "nickname", "description");
                org.springframework.data.domain.Page<UserDocument> documents = userRep.search(builder, pageable);
                //jpa 的page 转为 mybatics plus 的page
                pageData = new Page(page.getCurrent(), page.getSize(), documents.getTotalElements());
                pageData.setRecords(documents.getContent());
                break;
            case SearchConstants.Movie:
                //构建搜索条件
                MultiMatchQueryBuilder builder2 = QueryBuilders.multiMatchQuery(keyword, "mName", "types", "overview");
                org.springframework.data.domain.Page<MovieDocument> movieDocuments = movieRep.search(builder2, pageable);
                pageData = new Page(page.getCurrent(), page.getSize(), movieDocuments.getTotalElements());
                pageData.setRecords(movieDocuments.getContent());
                break;
            case SearchConstants.Video:
                //构建搜索条件
                MultiMatchQueryBuilder builder3 = QueryBuilders.multiMatchQuery(keyword, "title", "desc", "tname");
                org.springframework.data.domain.Page<VideoDocument> videoDocuments = videoRep.search(builder3, pageable);
                pageData = new Page(page.getCurrent(), page.getSize(), videoDocuments.getTotalElements());
                pageData.setRecords(videoDocuments.getContent());
                break;
        }
        return pageData;
    }


    @Override
    public int SaveVideotoEs(Video v) {
        VideoDocument videoDocument = new VideoDocument();
        BeanUtils.copyProperties(v, videoDocument);
        VideoDocument save = videoRep.save(videoDocument);
        if (save != null) {
            return 1;
        }
        return 0;
    }


    public int creatOrUpdateIndex(String bv){
        Query query = new Query();
        query.addCriteria(Criteria.where("bv").is(bv));
        Video video = mongoTemplate.findOne(query, Video.class);
        VideoDocument videoDocument = new VideoDocument();
        BeanUtils.copyProperties(video,videoDocument);
        VideoDocument save = videoRep.save(videoDocument);
        if(save!=null){
            return  1;
        }else {
            return  0;
        }
    }



}
